﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

///<summary>
///
///</summary>
public class AnimationComponent : MonoBehaviour
{
    [SerializeField]
    private Image image;
    [SerializeField]
    public List<Sprite> animationSprites = new List<Sprite>();
    public int index;
    public string path;
    public float PlaySpeed;
    private void OnEnable()
    {
        PlayAnimation();
    }

    private int AnimationAmount { get { return animationSprites.Count; } }
    public void PlayAnimation()
    {
        if (image == null) image = GetComponent<Image>();
        if (AnimationAmount < 1)
        {
            for (int i = 1; i < index; i++)
            {
                string spritePath = path + i;
                animationSprites.Add(Resources.Load<Sprite>(spritePath));

            }
        }
        StartCoroutine(PlayAnimationForwardIEnum());
    }

    //循环播放
    private IEnumerator PlayAnimationForwardIEnum()
    {
        int index = 0;//可以用来控制起始播放的动画帧索引
        gameObject.SetActive(true);
        while (true)
        {
            //当我们需要在整个动画播放完之后 重复播放后面的部分 就可以展现我们纯代码播放的自由性
            if (index < AnimationAmount - 1)
            {
                image.sprite = animationSprites[index];
                index++;
            }  
            else
            {
                index = 0;
            }
            yield return new WaitForSeconds(PlaySpeed);//等待间隔 控制动画播放速度
        }
    }

    //播放一次
    private IEnumerator PlayAnimationOnce()
    {
        int index = 0;//可以用来控制起始播放的动画帧索引
        gameObject.SetActive(true);
        while (true)
        {
            //当我们需要在整个动画播放完之后 重复播放后面的部分 就可以展现我们纯代码播放的自由性
            if (index < AnimationAmount - 1)
            {
                image.sprite = animationSprites[index];
                index++;
            }
            yield return new WaitForSeconds(PlaySpeed);//等待间隔 控制动画播放速度
        }
    }


}
